Input data validation

  • Step 1:
    It is used for preventing users from entering incorrect data

    Example 1

    
                      from odoo.exceptions import ValidationError
                      .... 
                      .... 
    
                      @api.constrains('date_end')
                      def _check_date_end(self):
                          for record in self:
                              if record.date_end < fields.Date.today():
                                  raise ValidationError("The end date cannot be set in the past")
    
                              
    
                    @api.constrains('name', 'description')
    def _check_description(self):
    for record in self:
        
    if record.name == record.description:
            
    raise ValidationError("Fields name and description must be different")
    
    

    the constraints specified to the field ‘age’ in a model check if the age is greater than 30 or not.

    
    @api.constrains('age')
    def _check_something(self):
        for record in self:
            if record.age > 30:
                raise ValidationError(“Age is greater than”)
    
            
    
            from odoo.exceptions import ValidationError
    @api.constrains(‘amount’)
    def _check_something(self):
        for record in self:
            if record.amount < 0:
                raise ValidationError(“Amount cannot be negative”)
    
            
    
            @api.constrains(field1, field2)
    def _check_values(self):
        for record in self:
            if record.field1 == record.field2:
                raise ValidationError("Fields field1 and field2 must be not be same")
    
            
    
            @api.constrains('instructor_id', 'attendee_ids')
        def _check_instructor_not_in_attendees(self):
            for r in self:
                if r.instructor_id and r.instructor_id in r.attendee_ids:
                    raise exceptions.ValidationError("A session's instructor can't be an attendee")
    
                
    
                from openerp.exceptions import ValidationError
    
                    @api.constraints('product_qty', 'cost_unit')
                    def _check_something(self):
                        for record in self:
                            if record.product_qty < 1:
                                raise ValidationError("Qty must be more than 0")